<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告框 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        closable
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="selectclassify">
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader
            v-model="selectedCate"
            :options="catelist"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 选项卡区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!--动态参数  -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isDisabled"
            @click="adddialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="dynamiclist" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 参数可选项 -->
                <el-tag
                  style="margin: 10px"
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加参数可选项 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editdialogShow(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removebyId(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isDisabled"
            @click="adddialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="staticList" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 参数可选项 -->
                <el-tag
                  style="margin: 10px"
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加参数可选项 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editdialogShow(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removebyId(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + caltitle"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="adddialogClose"
    >
      <el-form :model="addForm" :rules="addformrules" ref="addformRef">
        <el-form-item :label="caltitle" prop="attr_name" label-width="100px">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPrams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + caltitle"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editdialogClose"
    >
      <el-form :model="editForm" :rules="editformrules" ref="editformRef">
        <el-form-item :label="caltitle" prop="attr_name" label-width="100px">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPrams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  computed: {
    // 根据所选商品分类层级判断添加参数按钮是否禁用
    isDisabled() {
      // 选择的不是三级分类，按钮禁用
      if (this.selectedCate.length !== 3) return true
      return false
    },
    // 获取当前选择的三级商品分类的ID
    cateId() {
      if (this.selectedCate.length === 3) return this.selectedCate[2]
      return null
    },
    // 动态计算添加参数的标题
    caltitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  data() {
    return {
      // 商品分类数据列表
      catelist: [],
      // 双向绑定的级联选择器的选择的商品分类
      selectedCate: [],
      // 级联选择器的props属性配置对象
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        children: 'children',
        value: 'cat_id'
      },
      // tab选项卡的激活项,就是当前所选择的参数栏
      activeName: 'many',
      // 静态属性列表
      staticList: [],
      // 动态参数列表
      dynamiclist: [],
      // 控制添加参数的对话框隐藏
      adddialogVisible: false,
      // 添加参数表单
      addForm: {
        attr_name: ''
      },
      // 添加参数表单验证规则
      addformrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制修改参数对话框的隐藏
      editdialogVisible: false,
      // 修改参数的表单对象
      editForm: {
        attr_name: ''
      },
      // 修改参数表单验证规则
      editformrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取商品分类列表
    this.getCatelist()
  },
  methods: {
    // 获取商品分类数据列表
    async getCatelist() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.catelist = res.data
      // console.log(this.catelist)
    },
    // 当选择的商品分类改变时触发
    async handleChange() {
      this.getParamslist()
    },
    // 获取商品分类参数列表
    async getParamslist() {
      // 选中的不是三级分类，直接返回
      if (this.selectedCate.length !== 3) {
        this.selectedCate = []
        this.dynamiclist = []
        this.staticList = []
        return
      }
      // 选择的是三级分类时，发送axios请求参数列表数据
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      // 将参数的可选项分割成数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 控制参数可选项的添加输入框的隐藏
        item.inputVisible = false
        // 参数可选项的添加输入框的绑定值
        item.inputValue = ''
      })

      console.log(res.data)
      if (this.activeName === 'many') {
        this.dynamiclist = res.data
      } else {
        this.staticList = res.data
      }
    },
    // 当tab选项卡改变时触发
    handleClick() {
      // 获取参数列表
      this.getParamslist()
    },
    // 点击添加按钮，添加参数
    addPrams() {
      this.$refs.addformRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.adddialogVisible = false
        this.getParamslist()
      })
    },
    // 添加参数对话框关闭
    adddialogClose() {
      this.$refs.addformRef.resetFields()
    },
    // 显示修改参数对话框
    async editdialogShow(params) {
      // 根据ID查询参数
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${params.attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message.error('查询参数失败')
      // 将查询到的参数赋值给修改表单参数对象
      this.editForm = res.data
      // console.log(this.editForm)
      this.editdialogVisible = true
    },
    editdialogClose() {
      this.$refs.editformRef.resetFields()
    },
    // 点击确定按钮，修改参数
    editPrams() {
      // 对表单进行预验证
      this.$refs.editformRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamslist()
        this.editdialogVisible = false
      })
    },
    // 点击删除按钮，删除参数
    async removebyId(id) {
      // 删除弹框
      await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${id}`
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.getParamslist()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击添加参数可选项时，显示输入框
    showInput(row) {
      row.inputVisible = true
      // this.$nextTick是当页面中的元素被重新渲染后执行里面的回调函数
      this.$nextTick((_) => {
        //  即当input输入框被渲染到页面后再让其获得焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 发送编辑参数可选项的请求
    async saveAttrVals(row) {
      // 发送修改参数请求，添加参数可选项
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数选项失败')
      }
      this.$message.success('修改参数选项成功')
    },
    // 当按下回车或输入框失去焦点时，隐藏输入框
    async handleInputConfirm(row) {
      // 如果输入的值不合法，则清空直接返回，不做下一步操作
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 将添加的可选项添加到参数可选项数组中
      row.attr_vals.push(row.inputValue.trim())
      // console.log(this.staticList)
      // 发送修改参数请求，添加参数可选项
      this.saveAttrVals(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    // 删除参数可选项,i为要删除的数据的attr_vals数组的索引
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      // console.log(this.staticList)
      // 发送编辑参数请求，删除参数项
      this.saveAttrVals(row)
    }
  }
}
</script>

<style lang="less" scoped>
.selectclassify {
  margin: 18px 0;
}
.input-new-tag {
  width: 100px;
}
</style>
